//
//  CZEmoticonKeyBoard.swift
//  Weibo28
//
//  Created by Apple on 16/5/20.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

//  重用标记
private let CZEmoticonCollectionViewCellIdentifier = "CZEmoticonCollectionViewCellIdentifier"

//  表情键盘

class CZEmoticonKeyBoard: UIView {
    //  表情键盘toolbar
    private lazy var toolBar: CZEmoticonToolBar = {
        let view = CZEmoticonToolBar(frame: CGRectZero)
        return view
    }()
    //  表情视图
    private lazy var emoticonCollectionView: UICollectionView = {
        
        let flowLayout = UICollectionViewFlowLayout()
        //  指定水平方向滚动
        flowLayout.scrollDirection = .Horizontal
        
        let view = UICollectionView(frame: CGRectZero, collectionViewLayout: flowLayout)
        view.backgroundColor = self.backgroundColor
        //  开启分页模式
        view.pagingEnabled = true
        //  去掉水平滚动条
        view.showsHorizontalScrollIndicator = false
        //  去掉垂直滚动条
        view.showsVerticalScrollIndicator = false
        //  去掉弹簧效果
        view.bounces = false
        
        //  注册cell
        view.registerClass(CZEmoticonCollectionViewCell.self, forCellWithReuseIdentifier: CZEmoticonCollectionViewCellIdentifier)
        //  数据源代理
        view.dataSource = self
        //   设置代理
        view.delegate = self
        return view
        
    }()
    
    //  分页控件
    private lazy var pageControl: UIPageControl = {
        
        let ctr = UIPageControl()
        ctr.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        ctr.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        

        return ctr
    
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        backgroundColor = UIColor(patternImage: UIImage(named: "emoticon_keyboard_background")!)
        
        //  默认选中表情类型
        let indexPath: NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
        setPageControlData(indexPath)
        
        addSubview(toolBar)
        addSubview(emoticonCollectionView)
        addSubview(pageControl)
        
        emoticonCollectionView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        
        toolBar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(self)
            make.leading.equalTo(self)
            make.trailing.equalTo(self)
            make.height.equalTo(40)
        }
        
        pageControl.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
            make.height.equalTo(10)
        }
        
        toolBar.didSelectedEmoticonButtonClosure = { [weak self] (type: CZEmoticonToolBarButtonType) in
        
            let indexPath: NSIndexPath
            switch type {
            case .Normal:
                print("Normal")
                indexPath = NSIndexPath(forItem: 0, inSection: 0)
            case .Emoji:
                print("Emoji")
                indexPath = NSIndexPath(forItem: 0, inSection: 1)
            case .Lxh:
                print("Lxh")
                indexPath = NSIndexPath(forItem: 0, inSection: 2)
            }
//            print(self)
            //  滚动到指定位置
            self?.emoticonCollectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
            //  设置pagecontrol数据
            self?.setPageControlData(indexPath)
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //  获取布局方式
        let flowLayout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        //  没有cell大小就和我们表情视图的大小一样
        flowLayout.itemSize = emoticonCollectionView.size
        //  设置水平和
        flowLayout.minimumInteritemSpacing = 0
        //  垂直间距
        flowLayout.minimumLineSpacing = 0
        
        
    }
    
    //  设置pageControl数据
    private func setPageControlData(indexPath: NSIndexPath) {
        pageControl.numberOfPages = CZEmoticonTools.sharedTools.allEmoticons[indexPath.section].count
        pageControl.currentPage = indexPath.item
    
    }

}

extension CZEmoticonKeyBoard: UICollectionViewDataSource, UICollectionViewDelegate {
    
    //  返回多少组
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        //  只有三种类型的表情
        return CZEmoticonTools.sharedTools.allEmoticons.count
    }
    //  每组返回多少页
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return CZEmoticonTools.sharedTools.allEmoticons[section].count
    }
    
    //  创建cell
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CZEmoticonCollectionViewCellIdentifier, forIndexPath: indexPath) as! CZEmoticonCollectionViewCell
        cell.indexPath = indexPath
        //  设置表情数组元素
        cell.emotions = CZEmoticonTools.sharedTools.allEmoticons[indexPath.section][indexPath.item]
        return cell
        
    }
    
    //   监听滚动获取cell
    func scrollViewDidScroll(scrollView: UIScrollView) {
        
       // print(scrollView.contentOffset.x)
        let contentOffSetX = scrollView.contentOffset.x
        
        //  获取当前显示cell, 无序的,需要我们进行排序然后在判断cell哪个显示的多
        let cells = emoticonCollectionView.visibleCells().sort { (firstCell, secondCell) -> Bool in
            //  根据frame的x 进行排序
            return firstCell.x < secondCell.x
        }
    
        
        //  判断哪个显示多
        if cells.count == 2 {
            //  获取第一个cell
            let firstCell = cells.first!
            //  获取第二个cell
            let secondCell = cells.last!
            
            let firstCellContentOffSetX  = abs(firstCell.x - contentOffSetX)
            let secondCellContentOffSetX = abs(secondCell.x - contentOffSetX)
            
          
            
            
            //  如果第一个差值小于我们第二个差值,则第一个cell显示多
            let indexPath: NSIndexPath
            if firstCellContentOffSetX < secondCellContentOffSetX {

                indexPath = emoticonCollectionView.indexPathForCell(firstCell)!
            } else {

                indexPath = emoticonCollectionView.indexPathForCell(secondCell)!
            }
            
            //  获取indexpath对应的section
            let sction = indexPath.section
            
            //  设置按钮选中
            toolBar.selectEmotionButtonWithSection(sction)
            setPageControlData(indexPath)
        }
        
        
        
    }
    
}


